<?php
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://doc.swoft.org
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Controllers;

use Swoft\Http\Server\Bean\Annotation\Controller;
use Swoft\Http\Server\Bean\Annotation\RequestMapping;
use Swoft\Http\Server\Bean\Annotation\RequestMethod;
use Swoft\HttpClient\Client;
// use Swoft\View\Bean\Annotation\View;
// use Swoft\Http\Message\Server\Response;
use Swoft\Db\Db;
use Swoft\Db\Query;
use Swoft\App;
use Swoft\Log\Log;

/**
 * Class DealOrderController
 * @Controller(prefix="/dealorder")
 * @package App\Controllers
 */
class DealOrderController
{
    /**
     * this is a example action. access uri path: /dealOrder
     * @RequestMapping(route="/dealOrder", method=RequestMethod::GET)
     * @return array
     */
    public function index(): array
    {
        return ['item0', 'item1'];
    }

    /**
     * 订单处理
     * @RequestMapping(route="/sendorder/{table}[/{id}]")
     * @param string $table
     * @param int $id
     * @return array
     */
    public function sendOrder(string $table = 'o_realtime', int $id = 0): array
    {
        if (!in_array($table, ['o_realtime', 'o_flowtime', 'o_lifetime'])) {
            throw new \Exception('订单表错误', 1);
        }

        // 查询订单
        if ($id) {
            $order = Db::query("SELECT id,shopid,bid,bidhis,parvalue,retvalue,shoptype,ext,orderid2,cardpwd,inprice,qdprice,orderid,account,isbd,operators from {$table} where id = :id AND `status` = 0 limit 1", ['id' => $id])->getResult();
        } else {
            $order = Db::query("SELECT id,shopid,bid,bidhis,parvalue,retvalue,shoptype,ext,orderid2,cardpwd,inprice,qdprice,orderid,account,isbd,operators from {$table} where `status` = 0 AND bid NOT IN ('SGBDHF2','SGBDHF3','SGBDHFQ', 'TMYD','TMYD3') limit 1")->getResult();
        }
        if (empty($order)) {
            throw new \Exception('无满足条件订单', 1);
        }
        $order = $order[0];

        $tables = \Jpay\Helper\get_shop_table($order['shoptype']);

        /*if ($tables['orderTable'] != $table) {
            throw new \Exception('订单表不一致', 1);
        }*/

        if ($table == 'o_flowtime') {
            $addFields = ',price';
        } else {
            $addFields = '';
        }

        // 查询充值渠道信息
        $sql = "SELECT inprice,bid,`url`,outid,disprice{$add_fields} FROM {$tables['channelTable']} ";
        if (strlen($order['bid']) > 1) { // 订单已配置充值渠道
            $where = " WHERE shopid = :shopid AND bid = :bid AND switch = 1 LIMIT 1";
        } else { // 订单未配置充值渠道
            if (strlen(trim($order['bidhis'], ',')) < 1) { // 无历史充值渠道
                $where = " WHERE shopid = :shopid AND switch = 1 ORDER BY inprice LIMIT 1";
            } else { // 有历史充值渠道
                $bidHis = implode("','", explode(',', trim($order['bidhis'], ',')));
                $where = " WHERE shopid = :shopid AND bid NOT IN ('{$bidHis}') AND switch = 1 ORDER BY inprice LIMIT 1";
            }
        }
        $channel = Db::query($sql.$where, ['shopid' => $order['shopid'], 'bid' => $order['bid']])->getResult();
        if (empty($channel)) { // ORDER FAIL
            $orderStatus = 3;
            $failDesc = '未查询到充值渠道';
            $this->fail($table, $order['id'], $order['bid'], $failDesc);
            throw new \Exception($order['id'].'#'.$failDesc, 3);
        }
        $qdprice = $channel[0]['inprice'];
        $disprice = $channel[0]['disprice'];
        $pricedp = $channel[0]['pricedp'];
        $pricendp = $channel[0]['pricendp'];
        $price = $channel[0]['price'];
        $bid = strtoupper($channel[0]['bid']);
        $url = $channel[0]['url'];
        $pccord = $channel[0]['outid'];
        if ($order['shoptype'] == 31) {
            // Q币特殊处理
            $qdprice = bcmul(floor($order['parvalue']), $qdprice, 4);
        }

        // 更新订单为充值中
        $now = date('Y-m-d H:i:s');
        $updateResult = Db::query("UPDATE {$table} SET `status` = 1,rcvtime = '{$now}',bid = '{$bid}',qdprice = {$qdprice} WHERE id = {$order['id']} AND `status` = 0")->getResult();
        if (!$updateResult) {
            throw new \Exception($order['id'].'#更新订单为充值中失败', 1);
        }

        // 查询用户配置信息
        $user = Db::query("SELECT * FROM m_userapi WHERE userid = {$order['userid']} LIMIT 1")->getResult();
        if (empty($user)) { // ORDER FAIL
            $orderStatus = 3;
            $failDesc = '未查询到用户信息';
            $this->fail($table, $order['id'], $bid, $failDesc);
            throw new \Exception($order['id'].'#'.$failDesc, 3);
        }
        $user = $user[0];
        // 针对流量计算真实成本 costprice
        if ($table == 'o_flowtime') {
            if ($user['bill'] == 1) { // 1=带票
                if (bccomp($pricedp, $qdprice, 3) == 0) {
                    // 带票价格=渠道进价 => 带票渠道
                    $costprice = $qdprice;
                } else {
                    $costprice = $pricedp;
                }
            } else {
                if (bccomp($pricedp, $qdprice, 3) == 0) {
                    $costprice = $pricendp;
                } else {
                    $costprice = $qdprice;
                }
            }
        } else {
            $costprice = $qdprice;
        }

        // 渠道进价大于售价直接失败
        $checkLoss = true; // 亏损检查标记
        if (!in_array($order['userid'], ['1', '10000', '10009', '10010', '10011', '10012', '10013', '10014', '10016', '10017', '10018', '10019', '10020', '10021', '4', '118', '120', '2911', '8344', '8345', '8346', '123', '124', '125', '126'])) { // 非特定商户
            if (in_array($bid, ['UNITEL', 'YDCARD', 'DXTEL'])) $checkLoss = false;
            if (array_intersect(explode(',', $order['bidhis']), ['XCFT','TMALL','GMZT','JHAN','TLLBD','ZFBZF','WYKL'])) {
                $checkLoss = false;
            }
            if ($table == 'o_flowtime') {
                if ($user['bill'] != 1 && bccomp($order['inprice'], bcmul($qdprice, '0.965', 3), 3) >= 0) {
                    $checkLoss = false;
                }
            }
            // $isTrue = ($order['userid'] == '7' && $order['operators'] == '山西移动' && $order['parvalue'] >= 50 && $order['parvalue'] <= 500);
            // $isTrue = $order['userid'] == 85 && $order['operators'] == '广东移动' && $order['parvalue'] >= 200 && $order['parvalue'] <= 500;
            if ($order['userid'] == 85 && $order['operators'] == '广东移动' && $order['parvalue'] >= 100 && $order['parvalue'] <= 500) {
                $checkLoss = false;
            }
            // if ($checkLoss && bccomp($qdprice, $order['inprice'], 3) > 0 && !$isTrue) {
            if ($checkLoss && bccomp($qdprice, $order['inprice'], 3) > 0) {
                $isLoss = true;
            }
        } else { // 特定商户
            if (in_array($order['userid'], ['4', '118', '120', '2911', '8344'])) { // 话费特定商户亏损检查
                $rebatePrice = Db::query("SELECT discount FROM {$tables['rebateTable']} WHERE userid = {$order['userid']} AND shopid = '{$order['shopid']}' LIMIT 1")->getResult();
                if (bccomp($rebatePrice[0]['discount'], '0', 2) > 0 && bccomp($rebatePrice[0]['discount'], $qdprice, 3) < 0) {
                    // 密价表 discount=0 以渠道进价 inprice 为订单售价
                    // 密价表 discount>0 以密价为订单售价 此时需检查订单亏损
                    $isLoss = true;
                }
                $charge = $rebatePrice[0]['discount']; // 订单应收款/售价
            }
        }
        if ($isLoss) { // ORDER FAIL
            $failDesc = '渠道进价大于售价失败';
            $this->fail($table, $order['id'], $bid, $failDesc);
            throw new \Exception($order['id'].'#'.$failDesc, 3);
        }

        // 提交上游充值
        $orderPrefix = 'JYT';
        $amount = $order['parvalue'];
        if ($order['isbd'] == 1) {
            $orderPrefix = 'UFO';
            $amount = bcsub($order['parvalue'], $order['retvalue'], 0);
        }
        // 卡充渠道
        if (in_array($bid, ['YDCARD','DXTEL','UNITEL','OFCAR']) && stripos($order['ext'], 'DXDC') === false) {
            // code
        }
        // 提交参数
        $submitData = http_build_query([
            'orderid' => $orderPrefix.$order['id'],
            'account' => $order['account'],
            'amount' => $amount,
            'price' => $price,
            'area' => iconv('utf-8', 'gbk', $order['operators']),
            'inprice' => $order['inprice'],
            'shoptype' => $order['shoptype'],
            'cardno' => $order['cardno'],
            'cardpwd' => $order['cardpwd'],
            'pccord' => $pccord,
            'qdprice' => $qdprice,
            'numcheck' => $numcheck,
            'userid' => $order['userid'],
        ]);
        // 检查提交地址
        if (strlen($url) < 10) {
            $domain = 'http://if3.jieyitong.net/';
            switch ($table) {
                case 'o_realtime':
                    $route = 'api/submit/'.strtolower($bid).'.php';
                    break;
                case 'o_flowtime':
                    $route = 'api/submit/flow/'.strtolower($bid).'.php';
                    break;
                case 'o_lifetime':
                    $route = 'api/submit/zgsh/'.strtolower($bid).'.php';
                    break;
            }
            if ($ext == 'DXDC' && $bid == 'YDCARD') $route = 'api/submit/ydcard/dxdc.php';
            $url = $domain.$route;
        }
        // 提交上游充值
        $client = new Client(['timeout' => 20]);
        $response = $client->get($url.'?'.$submitData)->getResult();
        // $response = iconv('GBK', 'UTF-8//IGNORE', $response);
        if (mb_detect_encoding($response, 'ASCII,GB2312,GBK,UTF-8') == 'EUC-CN') {
            // $response = iconv('GB2312', 'UTF-8//IGNORE', $response);
            $response = mb_convert_encoding($response, 'UTF-8', 'EUC-CN');
        }
        $ostatus = str_substr($response, '<ostatus>', '</ostatus>');
        $orderid2 = str_substr($response, '<orderid2>', '</orderid2>');
        $faildesc = str_substr($response, '<faildesc>', '</faildesc>');
        $orderext = str_substr($response, '<orderext>', '</orderext>');
        $rnumcheck = str_substr($response, '<balance>', '</balance>');
        $gomeprice = str_substr($response, '<qdprice>', '</qdprice>');
        return [$table, $id, 'SUCCESS'];
    }

    /**
     * 订单主动查询
     * @RequestMapping(route="refresh/{table}[/{id}]")
     * @param string $table
     * @param int $id
     * @return array
     */
    public function refresh(): array
    {
        return [];
    }

    private function success(string $table, int $id): bool
    {
        return false;
    }

    private function fail(string $table, int $id, string $bid, string $failDesc = '', string $ext = ''): bool
    {
        return false;
    }

}
/* END */